package com.lz.sports.vm

import android.text.Editable
import android.text.TextUtils
import android.widget.CompoundButton
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.library.extension.APP
import com.lz.sports.LogUtils
import com.lz.sports.R
import com.lz.sports.bean.Examinee
import com.lz.sports.bean.QueryData
import com.lz.sports.core.ProjectManager
import com.lz.sports.core.VerifyManager
import com.lz.sports.db.ExamineeDatabase
import com.lz.sports.ui.checkmodel.ExamineeAndCardInfo
import com.lz.sports.utils.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.*

class QueryViewModel : BaseViewModel<BaseModel>()  {

    private val examPlanId = ProjectManager.examPlanId()

    //考区ID
    private val examAreaId = ProjectManager.examAreaId()

    //考点ID
    private val examSiteId = ProjectManager.examSiteId()

    //搜索关键词, 清除, 搜索状态
    val keywordStr = MutableLiveData<String>("")
    var showClear = MutableLiveData(false)
    val searchEnabled = MutableLiveData(false)

    //签到, 检录, 考试, 缺考
    val selectSign = MutableLiveData(false)
    val selectCheck = MutableLiveData(false)
    val selectExam = MutableLiveData(false)
    val selectLack = MutableLiveData(false)

    //搜索关键字
    private var listJob: Job? = null
    private var keyword: String? = null

    //所有学生数量
    val totalStr = MutableLiveData<String>()

    //查询列表
    val examineeList = MutableLiveData<List<QueryData>>()

    //检录方式
    val queryType = VerifyManager.queryModel().type

    //人脸识别去匹配监听
    val examineeAndCardInfo = MutableLiveData<ExamineeAndCardInfo>()

    fun afterTextChanged(editable: Editable) {
        showClear.value = editable.isNotEmpty()
    }

    fun onCheckedChanged(cb: CompoundButton, isChecked: Boolean) {
        LogUtils.i("${selectSign.value}, ${selectCheck.value}, ${selectExam.value}, ${selectLack.value}")
        searchEnabled.value = when (cb.id) {
            R.id.cb_sign -> selectCheck.value!! || selectExam.value!! || selectLack.value!!
            R.id.cb_check -> selectSign.value!! || selectExam.value!! || selectLack.value!!
            R.id.cb_exam -> selectSign.value!! || selectCheck.value!! || selectLack.value!!
            else -> selectSign.value!! || selectCheck.value!! || selectExam.value!!
        } || isChecked
    }

    private fun findExamineeList() {
        listJob?.cancel()

        listJob = launch {
            flow {
                emit(
                    ExamineeDatabase.get().queryAll(
                        selectSign.value!!, selectCheck.value!!, selectExam.value!!, selectLack.value!!,
                        keywordStr.value!!.trim(), examPlanId, examAreaId, examSiteId
                    )
                )
            }.flowOn(Dispatchers.IO)
                .onStart {
                    updateDialogLoading(true)
                }.onCompletion {
                    updateDialogLoading(false)
                }.collect {
                    examineeList.value = it
                    var maleCount = 0
                    it.forEach { data -> if (data.examineeInfo().isMale()) maleCount++ }
                    totalStr.value = APP.getString(R.string.manager_total, it.size, maleCount, it.size - maleCount)
                }
        }
    }

    fun selectAll() {
        selectSign.value = true
        selectCheck.value = true
        selectExam.value = true
        selectLack.value = true
    }

    fun search() {
        this.keyword = keywordStr.value?.trim()
        findExamineeList()
    }

    fun clearSearch() {
        if (!TextUtils.isEmpty(keyword)) {
            keyword = null
        }
    }

    fun searchResult(idCardInfo: IDCardInfo) {
        keywordStr.value = idCardInfo.num
        search()
    }

    fun searchExamineeResult(examinee: Examinee) {
        keywordStr.value = examinee.idCard
        search()
    }

/*    //查询考生信息
    fun findExamineeByIDCardInfo(idCardInfo: IDCardInfo): Examinee? {
        val examinee = ExamineeDatabase.get().examineeWithResultInspect(examPlanId, examAreaId, examSiteId, idCardInfo.num)
        if (examinee == null) {
            launch {
                ToastUtils.showMyToast(R.string.inspect_in_none, Toast.LENGTH_SHORT)
            }
        }
        return examinee
    }*/

    //人脸识别信息
    fun examineeFace(idCardInfo: IDCardInfo) {
        launch {
            val asyncJob = async(Dispatchers.Default) {
                ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
            }
            val examinee = asyncJob.await()
            if (examinee != null) {
                examineeAndCardInfo.value = ExamineeAndCardInfo(examinee, idCardInfo)
            } else {
                ToastUtils.showMyToast(R.string.inspect_in_none, Toast.LENGTH_SHORT)
            }
        }
    }

}